package com.taoyige.ui;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.taoyige.AppConfig;
import com.taoyige.AppContext;
import com.taoyige.AppException;
import com.taoyige.R;
import com.taoyige.bean.AlipayResult;
import com.taoyige.bean.Order;
import com.taoyige.bean.URLs;
import com.taoyige.common.AlipaySignUtils;
import com.taoyige.common.CalendarUtil;
import com.taoyige.common.NumberFormat;
import com.taoyige.common.UIHelper;
import com.taoyige.widget.LoadingDialog;

/**
 * 订单详情
 * @author zhuxun
 * @version 1.0
 * @date 2014-11-25 上午9:56:40
 */
public class OrderDetailActivity extends BaseActivity {
	
	private AppContext appContext;
	private Handler handler;
	private LoadingDialog loading;
	
	private ImageButton returnBack;
	private ImageButton homePage;
	private TextView userHeadText;
	private String orderId;
	private String uid;
	private LinearLayout orderDetailOperationLl;
	
	private Button operationRecepit;
	private Button operationTrack;
	
	private TextView orderNo;
	private TextView orderStatus;
	private ImageView orderPayMethod;
	private TextView orderTime;
	private ImageView orderProductImageUrl;
	private TextView orderProductTitle;
	private TextView orderProductPrice;
	private TextView orderProductCount;
	private TextView orderRecipientName;
	private TextView orderRecipientMobile;
	private TextView orderRecipientAddr;
	private TextView orderCount;
	private TextView orderTotalPrice;
	private TextView orderExpressCost;
	private TextView orderTotalMoney;
	
	private View orderOperationCancel;
	private View orderOperationDelivered;
	private View orderOperationNoPaid;
	
	private Button operationBuy;
	
	private LinearLayout orderDetailLl;
	private LinearLayout orderDetailInfoLi;
	
	private Order order;
	private LinearLayout orderdetailbody;
	private RelativeLayout orderdetailbodyfooter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		appContext=(AppContext) getApplication();
		setContentView(R.layout.order_detail);
		
		this.initView();
		this.initData();
	}
	
	private void initView(){
		orderId = getIntent().getStringExtra("orderId");
		uid = getIntent().getStringExtra("uid");
		
		returnBack=(ImageButton)findViewById(R.id.user_hear_return_back);
		homePage=(ImageButton)findViewById(R.id.user_hear_homePage);
		userHeadText=(TextView)findViewById(R.id.user_hear_text);
		userHeadText.setText("订单详情");
		orderdetailbody=(LinearLayout)findViewById(R.id.order_detail_body);
		orderdetailbodyfooter=(RelativeLayout)findViewById(R.id.order_detail_body_footer);
		returnBack.setOnClickListener(returnListener);
		homePage.setOnClickListener(homeListener);
		
		if (!appContext.isNetworkConnected()){
			orderdetailbody.setVisibility(View.INVISIBLE);
			orderdetailbodyfooter.setVisibility(View.INVISIBLE);
			return;
		}	
		
		  orderNo=(TextView) findViewById(R.id.order_detail_id_value);
		  orderStatus=(TextView) findViewById(R.id.order_detail_orderstatus_value);
		  orderPayMethod=(ImageView) findViewById(R.id.order_pay_menthod_value);
		  orderTime=(TextView) findViewById(R.id.order_detail_ordertime_value);
		  orderProductImageUrl=(ImageView) findViewById(R.id.order_detail_pic);
		  orderProductTitle=(TextView) findViewById(R.id.order_detail_title);
		  orderProductPrice=(TextView) findViewById(R.id.order_detail_money_value);
		  orderProductCount=(TextView) findViewById(R.id.order_detail_pay_num);
		  orderRecipientName=(TextView) findViewById(R.id.order_detail_name_value);
		  orderRecipientMobile=(TextView) findViewById(R.id.order_detail_phone_value);
		  orderRecipientAddr=(TextView) findViewById(R.id.order_detail_address_value);
		  orderTotalPrice=(TextView) findViewById(R.id.order_buymoney_value);
		  orderExpressCost=(TextView) findViewById(R.id.order_freight_value);
		  orderTotalMoney=(TextView) findViewById(R.id.order_paymoney_value);
		
		  orderDetailLl=(LinearLayout) findViewById(R.id.order_detail_ll);
		  orderDetailInfoLi=(LinearLayout)findViewById(R.id.order_detail_info_ll);
		  
		orderDetailOperationLl=(LinearLayout)findViewById(R.id.order_detail_operation_ll);
		LayoutInflater inflater = getLayoutInflater();
		
		 orderOperationCancel=inflater.inflate(R.layout.order_cancel, null);
		 orderOperationDelivered=inflater.inflate(R.layout.order_edit, null);
		 orderOperationNoPaid=inflater.inflate(R.layout.order_buy, null);
		
		operationRecepit=(Button)orderOperationDelivered.findViewById(R.id.order_detail_operation_recepit);
		operationTrack=(Button)orderOperationDelivered.findViewById(R.id.order_detail_operation_track);
		
		operationBuy=(Button)orderOperationNoPaid.findViewById(R.id.order_detail_buy_button);
		
		orderDetailInfoLi.setVisibility(View.INVISIBLE);
	}
	

	private void initData() {
		handler = new Handler() {
			public void handleMessage(Message msg) {
				if (loading != null)
					loading.dismiss();
				if (msg.what == 1 && msg.obj != null) {
					 order=(Order) msg.obj;
					
					 orderNo.setText(orderId);
					 
					  orderTime.setText(CalendarUtil.format(new Date(order.getTimestamp())));
					  
					  UIHelper.showGoodsImage(orderProductImageUrl, URLs.STATIC_HOST+order.getProduct().getThumbImageUrl().get(0));
					  orderProductTitle.setText(order.getProduct().getTitle());
					  orderProductPrice.setText(order.getProduct().getPrice()+"");
					  orderProductCount.setText("数量：1");
					  orderRecipientName.setText(order.getAddressInfo().getName());
					  orderRecipientMobile.setText(order.getAddressInfo().getMobilephone());
					  
					  orderRecipientAddr.setText(order.getAddressInfo().getDetails());
					  orderTotalPrice.setText(order.getProduct().getPrice()+"");
					  orderExpressCost.setText("0");
					  orderTotalMoney.setText(order.getTotalPrice()+"");
					  
					  //orderStatus.setText(order.getStatus())
					 // orderPayMethod.setText(order.getPaymentPlatform());
					  
					  switch(order.getPaymentPlatform()){
						case AppConfig.PAY_PLATFFROM_ALIPAY:
							orderPayMethod.setImageResource(R.drawable.zhifubao);
							break;
						case AppConfig.PAY_PLATFFROM_WECHAT:
							orderPayMethod.setImageResource(R.drawable.zhifubao);
							break;
						
						}
					  
					  RelativeLayout.LayoutParams lp=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.MATCH_PARENT);
						//lp.setMargins(0,0,0,0);
						
						switch(order.getStatus()){
						case AppConfig.ORDER_UNPAID:
							orderStatus.setText(getString(R.string.orde_status_unpaid));
							
							new CountDownTimer((order.getTimer()-19*60*1000)-(order.getServerTime()-order.getTimestamp()),1000l) {
								@Override
								public void onTick(long millisUntilFinished) {
									if(millisUntilFinished/1000>60){
										long m=millisUntilFinished/(1000*60);
										long s=(millisUntilFinished%(1000*60))/1000;
										operationBuy.setText(NumberFormat.format(m+"")+":"+NumberFormat.format(s+"")+" "+getString(R.string.orderpay));
									}else{
										long s=(millisUntilFinished%(1000*60))/1000;
										operationBuy.setText("00:"+NumberFormat.format(s+"")+" "+getString(R.string.orderpay));
									}
									
								}
								@Override
								public void onFinish() {
									//cancelOrder(order);
									orderStatus.setText(getString(R.string.orde_status_closed));
									orderDetailOperationLl.removeView(orderOperationNoPaid);
									
								}
							}.start();
							
							
							//添加立即付款按钮
							orderDetailOperationLl.addView(orderOperationNoPaid);
							orderOperationNoPaid.setTag(order);
							orderOperationNoPaid.setOnClickListener(gotoPayListener);
							break;
						case AppConfig.ORDER_PAID:
							orderStatus.setText(getString(R.string.orde_status_paid));
							operationBuy.setText(getString(R.string.orde_refund));
							orderDetailOperationLl.addView(orderOperationNoPaid);
							orderOperationNoPaid.setTag(order);
							orderOperationNoPaid.setOnClickListener(returnGoodsListener);
							break;
						case AppConfig.ORDER_DELIVERED:
							orderStatus.setText(getString(R.string.orde_status_delivered));
							orderDetailOperationLl.addView(orderOperationDelivered);
							operationRecepit.setOnClickListener(recepitListener);
							operationTrack.setTag(order);
							operationTrack.setOnClickListener(trackListener);
							break;
						case AppConfig.ORDER_CHECKED:
							orderStatus.setText(getString(R.string.orde_status_checked));
							operationBuy.setText(getString(R.string.orde_return_goods));
							orderDetailOperationLl.addView(orderOperationNoPaid);
							orderOperationNoPaid.setTag(order);
							orderOperationNoPaid.setOnClickListener(returnGoodsListener);
							break;
						case AppConfig.ORDER_CLOSED:
							orderDetailLl.setLayoutParams(lp);
							orderStatus.setText(getString(R.string.orde_status_closed));
							break;
						case AppConfig.ORDER_DELETED:
							orderDetailLl.setLayoutParams(lp);
							orderStatus.setText(getString(R.string.orde_status_deleted));
							break;
						case AppConfig.ORDER_REFUND:
							orderDetailLl.setLayoutParams(lp);
							orderStatus.setText(getString(R.string.orde_status_refund));
							break;
						case AppConfig.ORDER_REFUND_SUCCESS:
							orderDetailLl.setLayoutParams(lp);
							orderStatus.setText(getString(R.string.orde_status_refund_success));
							break;
						case AppConfig.ORDER_RETURN_GOODS:
							orderDetailLl.setLayoutParams(lp);
							orderStatus.setText(getString(R.string.orde_status_return_goods));
							break;
						case AppConfig.ORDER_RETURN_GOODS_SUCCESS:
							orderDetailLl.setLayoutParams(lp);
							orderStatus.setText(getString(R.string.orde_status_return_goods_scueess));
							break;
						}
					  
						orderDetailInfoLi.setVisibility(View.VISIBLE);
				} else if (msg.obj != null) {
					((AppException) msg.obj).makeToast(OrderDetailActivity.this);
				}
				
			}
		};
		
		loading = new LoadingDialog(this);
		loading.show();
		new Thread() {
			public void run() {
				Message msg = new Message();
				try {
					  order= appContext.getOrderDetail(orderId, uid);
					msg.what = 1;
					msg.obj = order;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				handler.sendMessage(msg);
			}
		}.start();

	}

	
	public View.OnClickListener returnGoodsListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			UIHelper.ToastMessage(v.getContext(), v.getContext().getString(R.string.user_return_goods_refund));
		}
	};
	
	public View.OnClickListener cancelListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			UIHelper.showHomePage(v.getContext());
		}
	};
	
	
	public View.OnClickListener gotoPayListener = new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//UIHelper.showHomePage(v.getContext());
				//判断订单是否有效
				if(order==null){
					UIHelper.ToastMessage(appContext, R.string.msg_order_invalidate);
					return;
				}
				//一分钟的缓冲时间
				if(order.getServerTime()>order.getTimestamp()+order.getTimer()-60*1000){
					UIHelper.ToastMessage(appContext, R.string.msg_order_invalidate);
					return;
				}
				
				orderPay(v,order);
				
			}
		};
	
		private void orderPay(final View v,final Order o) {
			final Handler orderHandler = new Handler() {
				public void handleMessage(Message msg) {
					if (msg.what == 1 ) {
						if(msg.obj!=null){
							final Map<String, Object> map=(Map<String, Object>) msg.obj;
							AlipayResult resultObj = new AlipayResult((String) map.get("result"));
							String resultStatus = resultObj.getResultStatus();
							if (TextUtils.equals(resultStatus, "9000")) {
								//更新订单
								//Order oo=appContext.orderPaid(orderId);
								new Thread() {
									public void run() {
										Message msg = new Message();
										try {
											String orderId=(String) map.get("orderId");
											Order oo=appContext.orderPaid(orderId);
											msg.what = 1;
											msg.obj = oo;
										} catch (AppException e) {
											e.printStackTrace();
											msg.what = -1;
											msg.obj = e;
										}
									}
								}.start();
								
								UIHelper.showUserCenter(OrderDetailActivity.this,AppConfig.BADGE_ORDER_PAID);
								
							} else {
								if (TextUtils.equals(resultStatus, "8000")) {
									UIHelper.ToastMessage(appContext, appContext.getString(R.string.pay_ing));
								} else if(TextUtils.equals(resultStatus, "6001")){
									UIHelper.ToastMessage(appContext, appContext.getString(R.string.pay_cancel));
								}else{
									UIHelper.ToastMessage(appContext, appContext.getString(R.string.pay_failed));
								}
							}
							
						}else{
							((AppException) msg.obj).makeToast(appContext);
						}
					} else{
						UIHelper.ToastMessage(appContext,appContext.getString(R.string.app_run_code_error));
					}
					
				}
			};
			new Thread() {
				public void run() {
					Message msg = new Message();
						if(o!=null&&o.getId()!=null){
							String alipayOrderInfo= appContext.getAlipayOrderInfo(o);
							String sign =  appContext.sign(alipayOrderInfo);
							
							try {
								sign = URLEncoder.encode(sign, "UTF-8");
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
							}
							final String payInfo = alipayOrderInfo + "&sign=\"" + sign + "\"&"+AlipaySignUtils.getSignType();
							
							PayTask alipay = new PayTask((Activity)v.getContext());
							String result = alipay.pay(payInfo);
							Map<String, Object> map=new HashMap<String, Object>();
							map.put("result", result);
							map.put("orderId", o.getId());
							msg.obj = map;
							msg.what = 1;
						}else{
							msg.obj = null;
							msg.what = -1;
						}
					orderHandler.sendMessage(msg);
				}
			}.start();
		}
		
		public View.OnClickListener recepitListener = new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//更新订单信息，弹出提示 TODO
				UIHelper.ToastMessage(v.getContext(), v.getContext().getString(R.string.user_recepit));
			}
		};
		public View.OnClickListener trackListener = new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				UIHelper.showOrderTrack(v.getContext(), ((Order)v.getTag()).getId(), ((Order)v.getTag()).getUserID());
			}
		};
		
		private View.OnClickListener homeListener = new View.OnClickListener(){
			@Override
			public void onClick(View v){
				UIHelper.showHomePage(v.getContext());
			}
		};
		
		private View.OnClickListener returnListener = new View.OnClickListener(){
			@Override
			public void onClick(View v){
				UIHelper.showUser(v.getContext());
			}
		};
	public View.OnClickListener orderStatusListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			UIHelper.showOrderStatus(v.getContext(),((Order)v.getTag()).getId(),((Order)v.getTag()).getUserID());
		}
	};
	
	

	private void cancelOrder(final Order o){
		final Handler ohandler = new Handler() {
			public void handleMessage(Message msg) {
				if (loading != null)
					loading.dismiss();
				if (msg.what == 1 ) {
					if(msg.obj!=null){
						Order od=(Order) msg.obj;
						if(od.getResult().getErrorCode()==200){
							//更新数据
							UIHelper.ToastMessage(OrderDetailActivity.this, "已经取消该订单");
							//UIHelper.showUnpaidOrder(OrderDetailActivity.this);
						}else{
							UIHelper.ToastMessage(OrderDetailActivity.this, "取消订单失败，请重试!");
						}
							
					}else{
						((AppException) msg.obj).makeToast(OrderDetailActivity.this);
					}
				} else{
					UIHelper.ToastMessage(OrderDetailActivity.this, getString(R.string.app_run_code_error));
				}
				
			}
		};
		
		new Thread() {
			public void run() {
				Message msg = new Message();
				try {
					Order  order= appContext.orderCancel(o.getId(), o.getUserID());
					if(order!=null&&order.getResult().getErrorCode()==200){
						msg.what = 1;
						msg.obj = order;
					}else{
						msg.what = -1;
						msg.obj = null;
					}
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				ohandler.sendMessage(msg);
			}
		}.start();
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
